package de.bomzhi.mz.pflection;

import java.lang.ref.WeakReference;
import java.util.List;

import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.ui.IWorkbenchWindow;

import com.powerflasher.fdt.core.builder.IBuildListener;

import de.bomzhi.mz.pflection.views.FDTPflectionView;
import de.bomzhi.mz.pflection.views.IRefreshableView;

public class RefreshViewAfterBuild implements IBuildListener {

	WeakReference<IRefreshableView> viewRef = new WeakReference<IRefreshableView>(null);

	public void fullBuildComplete(IProject arg0) {
		refreshTheView();
	}

	private void refreshTheView() {
		FDTPflection.getDefault().getWorkbench().getDisplay().syncExec(new Runnable() {
			public void run() {
				IRefreshableView view = getView();
				if(view != null){
					view.refresh();
				}
			}
		});
	}

	private IRefreshableView getView() {
		IRefreshableView view = viewRef.get();
		if (viewRef.get() == null) {
			IWorkbenchWindow activeWorkbenchWindow = FDTPflection.getDefault().getWorkbench().getActiveWorkbenchWindow();
			view = (IRefreshableView) activeWorkbenchWindow.getActivePage().findView(FDTPflectionView.ID);
			viewRef = new WeakReference<IRefreshableView>(view);
		}
		return view;
	}

	public void incrementalBuildComplete(List<IFile> arg0) {
		refreshTheView();
	}

	public void fullBuildComplete(IProject project, int buildState) {
		refreshTheView();		
	}

}
